"use client";

import React, { useState, useEffect } from "react";
import { Input, Button, Pagination, message, Space, Form, Modal } from "antd";
import { useUser } from "../../context/userContext";
import api from "../../utils/api";
import Link from "next/link";
import { HeartOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons";
import fontStyle from "@/components/Font.module.css"; // 引入 CSS 模块
const { TextArea } = Input;

interface CommentItem {
  commentId: number;
  content: string;
  authorId: number;
  postId: number;
  parentId: number | null;
  parentAuthorId: number | null;
  likes: number;
  createdAt: string;
  updatedAt: string;
  replies: CommentItem[];
}

interface CommentProps {
  postId: string;
}

interface UserInfo {
  display_name: string;
  icon: string;
}

const Comments: React.FC<CommentProps> = ({ postId }) => {
  const [comments, setComments] = useState<CommentItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(3); // 每页显示3条
  const [userInfoMap, setUserInfoMap] = useState<Record<number, UserInfo>>({});
  const [commentContent, setCommentContent] = useState("");
  const [totalComments, setTotalComments] = useState(0);
  const [replyModalVisible, setReplyModalVisible] = useState(false);
  const [replyContent, setReplyContent] = useState("");
  const [replyParentId, setReplyParentId] = useState<number | null>(null);
  const [replyUserId, setReplyUserId] = useState<number | null>(null);
  const [commentError, setCommentError] = useState<string>("");
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [deleteCommentId, setDeleteCommentId] = useState<number | null>(null);
  const [updateModalVisible, setUpdateModalVisible] = useState(false);
  const [updateCommentId, setUpdateCommentId] = useState<number | null>(null);
  const [updateContent, setUpdateContent] = useState("");

  const { user } = useUser();
  const accessToken = user?.access_token;

  // 获取评论列表
  const fetchComments = async () => {
    setLoading(true);
    try {
      const response = await api.get("/comments/list", {
        params: {
          postId,
          page: String(page),
          pageSize: String(pageSize),
        },
      });

      if (response.status === 200) {
        setComments(response.data.comments);
        setTotalComments(response.data.total);
        await fetchUsersInfo(response.data.comments);
      }
    } catch (error) {
      console.error("获取评论失败:", error);
    } finally {
      setLoading(false);
    }
  };

  // 获取用户信息
  const fetchUsersInfo = async (comments: CommentItem[]) => {
    const authorIds = new Set<number>();

    const extractAuthorIds = (commentList: CommentItem[]) => {
      commentList.forEach((comment) => {
        if (!userInfoMap[comment.authorId]) {
          authorIds.add(comment.authorId);
        }
        if (comment.replies.length > 0) {
          extractAuthorIds(comment.replies);
        }
      });
    };

    extractAuthorIds(comments);

    try {
      const promises = Array.from(authorIds).map((id) =>
        api.get(`/users/info`, { params: { id } })
      );
      const responses = await Promise.all(promises);

      const newUserInfo: Record<number, UserInfo> = {};
      responses.forEach((response, index) => {
        if (response.status === 200) {
          newUserInfo[Array.from(authorIds)[index]] = response.data;
        }
      });
      setUserInfoMap((prev) => ({ ...prev, ...newUserInfo }));
    } catch (error) {
      console.error("获取用户信息失败:", error);
    }
  };

  // 监听 postId, page
  useEffect(() => {
    fetchComments();
  }, [postId, page]);

  // 分页处理
  const handlePageChange = (newPage: number) => {
    setPage(newPage);
  };

  // 发表一级评论
  const handlePostComment = async () => {
    if (!commentContent.trim()) {
      message.error("评论内容不能为空");
      return;
    }
    setCommentError("");

    try {
      const response = await api.post(
        "/comments/create",
        {
          content: commentContent,
          postId: postId,
          parentId: null,
          atUserId: null,
        },
        {
          headers: {
            Authorization: `Bearer ${accessToken}`,
          },
        }
      );

      if (response.data.success) {
        message.success("发表评论成功");
        setCommentContent("");
        fetchComments();
      } else {
        message.error("发表评论失败");
      }
    } catch (error) {
      console.error("发表评论失败:", error);
      message.error("发表评论失败");
    }
  };

  // 渲染评论和子评论
  const renderComments = (commentList: CommentItem[], indent = 0) => {
    return commentList.map((comment) => (
      <div
        key={comment.commentId}
        style={{
          padding: `${indent === 0 ? "10px 14px" : "8px 12px"}`,
          marginBottom: "8px",
          border: `1px solid ${indent > 0 ? "#ffffff" : "#D6A7A1"}`,
          borderRadius: "14px",
          backgroundColor: indent > 0 ? "#F5F0F0AA" : "#FFF",
          boxShadow: "0 1px 4px rgba(0, 0, 0, 0.03)",
          transition: "all 0.2s ease",
        }}
        className="hover:shadow-md hover:border-[#C69791]"
      >
        <Space direction="vertical" style={{ width: "100%" }}>
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
            }}
          >
            {/* 显示用户信息 */}
            <Link
              href={`/author/${comment.authorId}`}
              className={fontStyle.linkText}
              style={{ fontSize: "14px" }}
            >
              <span>
                {userInfoMap[comment.authorId]?.display_name || "加载中..."}
              </span>
            </Link>
          </div>
          {/* 显示评论内容 */}
          <div
            className={fontStyle.text}
            style={{ fontSize: "14px", margin: "6px 0", lineHeight: 1.2 }}
          >
            {comment.content}
          </div>
          {/* 显示评论喜欢 回复 编辑 删除 */}
          <div
            style={{
              display: "flex",
              gap: 12,
              fontSize: 12,
              color: "#666",
              marginBottom: "4px",
            }}
          >
            <span>
              <HeartOutlined
                style={{ color: "#D6A7A1", marginRight: 2, fontSize: 14 }}
              />
              {comment.likes}
            </span>
            <span
              style={{
                cursor: "pointer",
                color: "#888",
                display: "flex",
                alignItems: "center",
              }}
              onClick={() => {
                if (indent) {
                  setReplyParentId(comment.parentId);
                  setReplyUserId(comment.authorId);
                } else {
                  setReplyParentId(comment.commentId);
                  setReplyUserId(null);
                }
                setReplyModalVisible(true);
              }}
            >
              <span style={{ marginRight: 2 }}>回复</span>
            </span>
            {/* 仅非本人评论显示举报按钮 */}
            {user?.id !== comment.authorId && (
              <span
                style={{
                  cursor: "pointer",
                  color: "#888",
                  display: "flex",
                  alignItems: "center",
                }}
              >
                <Link
                  href={{ pathname: `/posts/${postId}/${comment.commentId}` }}
                  legacyBehavior
                >
                  <a style={{ color: "#888" }}>举报</a>
                </Link>
              </span>
            )}
            {/* 如果是当前用户的评论，显示编辑按钮 */}
            {user?.id === comment.authorId && (
              <span
                style={{
                  cursor: "pointer",
                  color: "#888",
                  display: "flex",
                  alignItems: "center",
                }}
                onClick={() => {
                  setUpdateCommentId(comment.commentId);
                  setUpdateContent(comment.content);
                  setUpdateModalVisible(true);
                }}
              >
                <EditOutlined style={{ marginRight: 2, fontSize: 14 }} />
                <span>编辑</span>
              </span>
            )}
            {/* 如果是当前用户的评论，显示删除按钮 */}
            {user?.id === comment.authorId && (
              <span
                style={{
                  cursor: "pointer",
                  color: "#e57373",
                  display: "flex",
                  alignItems: "center",
                }}
                onClick={() => {
                  setDeleteCommentId(comment.commentId);
                  setDeleteModalVisible(true);
                }}
              >
                <DeleteOutlined style={{ marginRight: 2, fontSize: 14 }} />
                <span>删除</span>
              </span>
            )}
          </div>
        </Space>
        {/* 递归调用，显示子评论 */}
        {comment.replies.length > 0 &&
          renderComments(comment.replies, indent + 1)}
      </div>
    ));
  };

  return (
    <div style={{ paddingRight: "5px" }}>
      <h3
        style={{
          fontSize: "16px",
          color: "#7a6e6e",
          paddingBottom: 6,
          borderBottom: "1px solid #D6A7A1",
        }}
      >
        评论
      </h3>

      {/* 局部滚动容器包裹 List */}
      <div
        style={{
          maxHeight: "25vh",
          overflowY: "auto",
          padding: 0,
          marginBottom: 16,
        }}
      >
        {loading ? (
          <div style={{ textAlign: "center", padding: 16 }}>
            <div className="inline-block animate-spin rounded-full h-6 w-6 border-b-2 border-[#D6A7A1]" />
            <p style={{ marginTop: 8, color: "#7A6E6E", fontSize: 13 }}>
              加载评论中...
            </p>
          </div>
        ) : comments.length === 0 ? (
          <div
            style={{
              textAlign: "center",
              padding: "20px 10px",
              color: "#7A6E6E",
              backgroundColor: "#F9F7F7",
              borderRadius: 6,
              minHeight: 80,
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <p style={{ fontSize: 14 }}>暂无评论，快来发表你的看法吧！</p>
          </div>
        ) : (
          renderComments(comments)
        )}
        {/* 分页器 */}
        <Pagination
          current={page}
          pageSize={pageSize}
          onChange={handlePageChange}
          total={totalComments}
          style={{
            marginTop: 12,
            display: "flex",
            justifyContent: "center",
            fontSize: 12,
          }}
          itemRender={(page, type, originalElement) => {
            if (type === "prev") {
              return <span>上一页</span>;
            }
            if (type === "next") {
              return <span>下一页</span>;
            }
            return originalElement;
          }}
        />
      </div>

      {/* 输入评论的文本框和按钮，底部对齐*/}
      <div
        style={{
          position: "fixed", // 固定到底部
          bottom: "6vh",
          width: "65%",
        }}
      >
        {/* 输入评论的文本框 */}
        <TextArea
          rows={2}
          placeholder="写下你的评论..."
          style={{
            marginTop: 12,
            borderRadius: 6,
            border: "1px solid #D6A7A1",
            padding: "10px 12px",
            fontSize: 14,
            transition: "all 0.3s",
            ":focus": {
              borderColor: "#C69791",
              boxShadow: "0 0 0 2px rgba(214, 167, 161, 0.2)",
            },
          }}
          value={commentContent}
          onChange={(e) => setCommentContent(e.target.value)}
        />
        {/* 发表评论按键 */}
        <Button
          type="primary"
          style={{
            marginTop: 8,
            backgroundColor: "#D6A7A1",
            borderColor: "#D6A7A1",
            borderRadius: 6,
            padding: "6px 16px",
            fontSize: 14,
            transition: "all 0.3s",
            ":hover": {
              backgroundColor: "#C69791",
              borderColor: "#C69791",
              transform: "translateY(-1px)",
            },
          }}
          onClick={handlePostComment}
        >
          发表评论
        </Button>
      </div>

      {/* 二级评论， 跳出弹窗 */}
      <Modal
        title="回复评论"
        visible={replyModalVisible}
        onOk={async () => {
          if (!replyContent.trim()) {
            setCommentError("评论内容不能为空");
            return;
          }
          setCommentError("");

          try {
            let finalContent = replyContent;
            if (replyUserId) {
              const displayName = userInfoMap[replyUserId]?.display_name || "";
              finalContent = `@${displayName}  ${finalContent}`;
            }

            const sendInfo = {
              content: finalContent,
              postId: postId,
              parentId: replyParentId,
              atUserId: replyUserId,
            };

            const response = await api.post("/comments/create", sendInfo, {
              headers: {
                Authorization: `Bearer ${accessToken}`,
              },
            });

            if (response.data.success) {
              message.success("回复成功");
              setReplyContent("");
              setReplyModalVisible(false);
              fetchComments();
            } else {
              message.error("回复失败");
            }
          } catch (error) {
            console.error("回复失败:", error);
            message.error("回复失败");
          }

          setReplyContent("");
          setReplyModalVisible(false);
          fetchComments();
        }}
        onCancel={() => {
          setReplyModalVisible(false);
          setReplyContent("");
        }}
        okButtonProps={{
          style: { backgroundColor: "#D6A7A1", borderColor: "#D6A7A1" },
        }}
      >
        <Form.Item
          validateStatus={commentError ? "error" : ""}
          help={commentError ? commentError : ""}
        >
          <TextArea
            rows={3}
            value={replyContent}
            onChange={(e) => {
              setReplyContent(e.target.value);
              setCommentError("");
            }}
            placeholder="输入你的评论..."
            style={{
              borderRadius: 6,
              border: "1px solid #D6A7A1",
              padding: "10px 12px",
              fontSize: 14,
            }}
          />
        </Form.Item>
      </Modal>

      {/* 删除评论的模态框 */}
      <Modal
        title="确认删除这条评论吗？"
        open={deleteModalVisible}
        onOk={async () => {
          if (deleteCommentId === null) return;

          try {
            const response = await api.delete("/comments/delete", {
              params: {
                commentId: deleteCommentId,
              },
              headers: {
                Authorization: `Bearer ${accessToken}`,
              },
            });

            if (response.data.success) {
              message.success("评论已删除");
              fetchComments();
            } else {
              message.error("删除失败");
            }
          } catch (error) {
            console.error("删除失败:", error);
            message.error("删除失败");
          } finally {
            setDeleteModalVisible(false);
            setDeleteCommentId(null);
          }
        }}
        onCancel={() => {
          setDeleteModalVisible(false);
          setDeleteCommentId(null);
        }}
        okText="删除"
        cancelText="取消"
        okButtonProps={{
          style: { backgroundColor: "#e57373", borderColor: "#e57373" },
        }}
        cancelButtonProps={{
          style: { color: "#666" },
        }}
      >
        <p style={{ color: "#333", lineHeight: 1.5, fontSize: 14 }}>
          此操作不可撤销，是否继续？
        </p>
      </Modal>

      {/* 编辑评论的模态框 */}
      <Modal
        title="编辑评论"
        visible={updateModalVisible}
        onOk={async () => {
          if (!updateContent.trim()) {
            message.error("评论内容不能为空");
            return;
          }

          try {
            const response = await api.put(
              "/comments/update",
              {
                commentId: updateCommentId,
                content: updateContent,
              },
              {
                headers: {
                  Authorization: `Bearer ${accessToken}`,
                },
              }
            );

            if (response.data.success) {
              message.success("评论已更新");
              setUpdateModalVisible(false);
              fetchComments();
            } else {
              message.error("更新失败");
            }
          } catch (error) {
            console.error("更新失败:", error);
            message.error("更新失败");
          }
        }}
        onCancel={() => {
          setUpdateModalVisible(false);
        }}
        okButtonProps={{
          style: { backgroundColor: "#D6A7A1", borderColor: "#D6A7A1" },
        }}
      >
        <Form.Item>
          <TextArea
            rows={3}
            value={updateContent}
            onChange={(e) => setUpdateContent(e.target.value)}
            placeholder="输入你的评论..."
            style={{
              borderRadius: 6,
              border: "1px solid #D6A7A1",
              padding: "10px 12px",
              fontSize: 14,
            }}
          />
        </Form.Item>
      </Modal>
    </div>
  );
};

export default Comments;
